// The core of the jsonql middleware
import { QUERY_NAME, MUTATION_NAME } from 'jsonql-constants'
import { resolveMethod } from 'jsonql-resolver'
import { getDebug } from '../utils'
const debug = getDebug('core')

/**
 * Top level entry point for jsonql Koa middleware
 * @param {object} config options
 * @return {mixed} depends whether if we catch the call
 */
export default function coreMiddleware(opts) {
  // ouput the middleware
  return async function(ctx, next) {
    if (ctx.state.jsonql.isReq) {
      const { contract, resolverType } = ctx.state.jsonql;
      debug('isJsonqlRequest', resolverType)
      if (resolverType === QUERY_NAME || resolverType === MUTATION_NAME) {
        // debug(`Is jsonql query`, contract, opts)
        // The problem is - the config is correct
        // but the contract return the previous one
        return resolveMethod(ctx, resolverType, opts, contract)
      }
    } else {
      await next()
    }
  }
}
